package com.etang.shtest;

import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.os.Build;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RadioButton;

import com.bizideal.smarthome.socket.SocketClient;
import com.bizideal.smarthome.socket.Utils.SpUtils;
import com.etang.shtest.dialogs.DialogMessage;
import com.etang.shtest.fragment.BarActivity;
import com.etang.shtest.tools.AppConfig;
import com.etang.shtest.tools.CodeView;
import com.etang.shtest.tools.DiyToast;
import com.etang.shtest.tools.MyDataBaseHelper;
import com.etang.shtest.tools.MySQLiteHelper;

import java.util.Locale;

import cn.bmob.v3.listener.LogInListener;

public class LoginActivity extends AppCompatActivity {
    private Button btn_login;
    private EditText et_user, et_pass, et_code_pass, et_ip;
    private ImageView iv_code_show, iv_yuyan_setting;
    private CheckBox cb_rember, cb_autologin;

    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR1)
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        setLanguage();//设置语言
        initView();//绑定控件
        initRemb();//检查记住密码、自动登录
        initImag();//创建验证码
        ///设置语言
        iv_yuyan_setting.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //创建单选框
                final AlertDialog.Builder builder = new
                        AlertDialog.Builder(LoginActivity.this);
                builder.setTitle("请选择你的语言\nPlease select a language\n言語を選んでください");
                builder.setSingleChoiceItems(new String[]{"Auto", "简体中文", "English", "日本語"},
                        Integer.valueOf(SpUtils.getValue(getApplicationContext(), "language", null)),
                        new DialogInterface.OnClickListener() {
                            //点击单选框某一项以后
                            public void onClick(DialogInterface dialogInterface, int i) {
                                //将选中项存入SharedPreferences，以便重启应用后读取设置
                                DiyToast.showToast(getApplicationContext(), "软件重启后应用新语言");
                                SpUtils.putValue(LoginActivity.this, "language", String.valueOf(i));
                                Intent intent = new Intent(LoginActivity.this, MainActivity.class);
                                intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                                startActivity(intent);
                                /* 重新在新的任务栈开启新应用
                                Intent intent = new Intent(MainActivity.this, MainActivity.class);
                                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
                                startActivity(intent);
                                android.os.Process.killProcess(android.os.Process.myPid()); */
                            }
                        });
                builder.show();
            }
        });
        //初始化验证码并显示
        iv_code_show.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                initImag();//创建验证码
            }
        });
        //登录按钮
        btn_login.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (et_ip.getText().toString().isEmpty() || et_code_pass.getText().toString().isEmpty() || et_pass.getText().toString().isEmpty() || et_user.getText().toString().isEmpty()) {
                    DiyToast.showToast(getApplicationContext(), "不能有空白项！");
                } else {
                    if (et_code_pass.getText().toString().equalsIgnoreCase(CodeView.code)) {
                        check_rember();
                        SocketClient.ip = et_ip.getText().toString();
                        if (MySQLiteHelper.rawQuery(LoginActivity.this, et_user.getText().toString(), et_pass.getText().toString())) {
                            startActivity(new Intent(getApplicationContext(), BarActivity.class));
                            overridePendingTransition(0, 0);//关闭跳转动画
                            finish();
                        }
                    } else {
//                        DialogMessage.showdialog(LoginActivity.this, "登录失败", "验证码错误");
                    }
                }
            }
        });
        cb_rember.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {

                } else {
                    cb_autologin.setChecked(false);
                }
            }
        });
        cb_autologin.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    cb_rember.setChecked(true);
                } else {
                    cb_rember.setChecked(false);
                }
            }
        });
    }

    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR1)
    private void setLanguage() {
        //读取SharedPreferences数据，默认选中第一项
        int language = Integer.valueOf(SpUtils.getValue(getApplicationContext(), "language", null));
        //根据读取到的数据，进行设置
        Resources resources = getResources();
        DisplayMetrics displayMetrics = resources.getDisplayMetrics();
        Configuration configuration = resources.getConfiguration();
        switch (language) {
            case 0:
                //自动获取
                configuration.setLocale(Locale.getDefault());
                break;
            case 1:
                //中文
                configuration.setLocale(Locale.CHINESE);
                break;
            case 2:
                //英文
                configuration.setLocale(Locale.ENGLISH);
                break;
            case 3:
                //日文
                configuration.setLocale(Locale.JAPANESE);
                break;
            default:
                break;
        }
        resources.updateConfiguration(configuration, displayMetrics);
    }

    /**
     * 创建验证码
     */
    private void initImag() {
        iv_code_show.post(new Runnable() {
            @Override
            public void run() {
                try {
                    Thread.sleep(2000);
                } catch (Exception e) {

                }
                int w = iv_code_show.getWidth();
                int h = iv_code_show.getHeight();
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        iv_code_show.setImageBitmap(CodeView.createBitmap(w, h));
                        et_code_pass.setText(CodeView.code);
                    }
                });
            }
        });
    }

    /**
     * 检查记住密码是否选中
     */
    private void check_rember() {
        if (cb_autologin.isChecked()) {
            //自动登录被选中
            SpUtils.putValue(getApplicationContext(), "autologin", "1");
            SpUtils.putValue(getApplicationContext(), "rember", "1");
            SpUtils.putValue(getApplicationContext(), "user", et_user.getText().toString());
            SpUtils.putValue(getApplicationContext(), "pass", et_pass.getText().toString());
            SpUtils.putValue(getApplicationContext(), "ip", et_ip.getText().toString());
        } else if (cb_rember.isChecked()) {
            //记住密码被选中
            SpUtils.putValue(getApplicationContext(), "autologin", "0");
            SpUtils.putValue(getApplicationContext(), "rember", "1");
            SpUtils.putValue(getApplicationContext(), "user", et_user.getText().toString());
            SpUtils.putValue(getApplicationContext(), "pass", et_pass.getText().toString());
            SpUtils.putValue(getApplicationContext(), "ip", et_ip.getText().toString());
        } else {
            //都没有选中
            SpUtils.putValue(getApplicationContext(), "autologin", "0");
            SpUtils.putValue(getApplicationContext(), "rember", "0");
            SpUtils.putValue(getApplicationContext(), "user", et_user.getText().toString());
            SpUtils.putValue(getApplicationContext(), "pass", et_pass.getText().toString());
            SpUtils.putValue(getApplicationContext(), "ip", et_ip.getText().toString());
        }
    }

    private void initRemb() {
        if (SpUtils.getValue(getApplicationContext(), "rember", null).toString().equals("1")) {
            cb_rember.setChecked(true);
            et_user.setText(SpUtils.getValue(getApplicationContext(), "user", null));
            et_pass.setText(SpUtils.getValue(getApplicationContext(), "pass", null));
            et_ip.setText(SpUtils.getValue(getApplicationContext(), "ip", null));
        }
        if (SpUtils.getValue(getApplicationContext(), "autologin", null).toString().equals("1")) {
            SocketClient.ip = SpUtils.getValue(getApplicationContext(), "ip", null);
            startActivity(new Intent(LoginActivity.this, BarActivity.class));
            overridePendingTransition(0, 0);//关闭跳转动画
            finish();
        }
    }

    public void login_exit(View view) {
        System.exit(0);
    }

    private void initView() {
        et_ip = (EditText) findViewById(R.id.et_login_ip);
        btn_login = (Button) findViewById(R.id.btn_login);
        et_code_pass = (EditText) findViewById(R.id.et_login_codepass);
        et_pass = (EditText) findViewById(R.id.et_login_passward);
        et_user = (EditText) findViewById(R.id.et_login_username);
        iv_code_show = (ImageView) findViewById(R.id.iv_code_show);
        iv_yuyan_setting = (ImageView) findViewById(R.id.iv_yuyan_setting);
        cb_autologin = (CheckBox) findViewById(R.id.cb_autologin);
        cb_rember = (CheckBox) findViewById(R.id.cb_rember);
    }

    public void reg(View view) {
        startActivity(new Intent(LoginActivity.this, RegActivity.class));
        overridePendingTransition(0, 0);//关闭跳转动画
    }
}